# -*- coding:utf-8 -*-
# TODO : cascade sur suppression Ventilation -> PlageHoraire
from django.db import models
from django.db.models import Sum
from django.template import Context, loader
from datetime import datetime, date

from formation.models import UniteFormation, ActiviteUf


###################
# Modèles Professeur
###################
class Professeur(models.Model):
    nom = models.CharField(max_length=50)
    prenom = models.CharField("Prénom", max_length=50)
    
    def __unicode__(self):
        return "%s %s" % (self.nom, self.prenom)

###################
# Modèles Horaire
###################
SCHOOL_YEAR_CHOICES = [(x,x) for x in [str(i)[2:]+"-"+str(i+1)[2:] for i in range (1991,2013)]]
class Horaire(models.Model):
    uf = models.ForeignKey(UniteFormation)
    intitule = models.CharField("Intitulé", max_length=200)
    annee_scolaire = models.CharField("Année scolaire", max_length=5, choices=SCHOOL_YEAR_CHOICES, default="12-13")
    organisation = models.IntegerField("Numéro d'organisation")
    
    def comptage_ventilation(self):
        acts = self.uf.activiteuf_set.exclude(categorie__istartswith="auto")
        for act in acts:
            act.periodes_ventilees = self.ventilation_set.filter(activite=act).aggregate(Sum("periodes"))['periodes__sum']
            act.periodes_autonomie = self.ventilation_set.filter(activite=act).aggregate(Sum("periodes_auto"))['periodes_auto__sum']
            act.periodes_horaire = self.plagehoraire_set.filter(activite_enseignement__activite__libelle__iexact=act.libelle).aggregate(Sum("periodes"))['periodes__sum']
            try:
                act.periodes_totales = act.periodes_ventilees + act.periodes_autonomie
            except TypeError:
                act.periodes_totales = 0.
        try:
            auto = self.uf.activiteuf_set.get(categorie__istartswith="auto")
            auto.periodes_ventilees = self.ventilation_set.aggregate(Sum("periodes_auto"))['periodes_auto__sum']
        except ActiviteUf.DoesNotExist:
            auto = None
        t = loader.get_template("grille_ventilation.html")
        c = Context({"activites":acts, "auto":auto})
        return t.render(c)

    comptage_ventilation.allow_tags = True
    
    def premier_dixieme(self):
        pd = self.uf.periodes//10
        cpt = 0
        for ph in self.plagehoraire_set.all():
            cpt += ph.periodes
            if cpt >= pd:
                return ph.jour
        return None

    def cinquieme_dixieme(self):
        pd = self.uf.periodes//2
        cpt = 0
        for ph in self.plagehoraire_set.all():
            cpt += ph.periodes
            if cpt >= pd:
                return ph.jour
        return None
    
    def __unicode__(self):
        return u"(%s) %s" % (self.annee_scolaire,self.intitule)

######################
# Modèles Ventilation
######################
SF_CHOICES = (
              ("D","Dotation"),
              ("F","Fond social Européen"),
              ("C","Convention"),
              ("E","Enseignement à Horaire Réduit"),
              )
TITRE_CHOICES = (
              ("R","R"),
              ("A","A"),
              ("B","B"),
              ("N","N"),
              ("3B","3B"),
              ("D","D"),
              ("A","A"),
              ("C","C"),
              )
SITUATION_CHOICES = (
              ("D","Définitif"),
              ("V","Stable - Vacant"),
              ("S","Stable"),
              ("I","Intérimaire"),
              )
class Ventilation(models.Model):
    horaire = models.ForeignKey(Horaire)
    professeur = models.ForeignKey(Professeur)
    sf = models.CharField("Source de financement", max_length=5, choices = SF_CHOICES, default="D")
    activite = models.ForeignKey(ActiviteUf)
    periodes = models.DecimalField("Périodes", max_digits=5, decimal_places=2, blank=True, null=True)
    periodes_auto = models.DecimalField("Autonomie", max_digits=5, decimal_places=2, blank=True, null=True)
    titre = models.CharField("Titre", max_length=2, choices=TITRE_CHOICES, default="B")
    situation = models.CharField("Situation administrative", choices=SITUATION_CHOICES, max_length=1, default="V")
    di = models.CharField("DI", max_length=5, blank=True, null=True)
    
    def __unicode__(self):
        return u"%s (%s)" % (self.activite.libelle,self.professeur)
    
######################
# Modèles Plage Horaire
######################
class PlageHoraire(models.Model):
    horaire = models.ForeignKey(Horaire)
    jour = models.DateField()
    heure_debut = models.TimeField(default="17:30:00")
    heure_fin = models.TimeField(default="21:00:00")
    pause = models.IntegerField("Temps de pause (min)", default=10)
    activite_enseignement = models.ForeignKey(Ventilation)
    periodes = models.DecimalField("Périodes", max_digits=5, decimal_places=2, blank=True, null=True)
    
    def save(self, *args, **kwargs):
        td = datetime.combine(date.today(),self.heure_fin) - datetime.combine(date.today(),self.heure_debut)
        self.periodes = (td.seconds/60. - self.pause)/50
        super(PlageHoraire, self).save(*args, **kwargs)   
    
    def __unicode__(self):
        return u"%s(%s)" % (self.activite_enseignement, self.periodes)
    
    class Meta:
        ordering = ["jour", "heure_debut"]
    
